package com.alm.handle.service.impl;

import com.alm.common.core.redis.RedisCache;
import com.alm.common.utils.SecurityUtils;
import com.alm.handle.core.domain.entity.SysDevInfo;
import com.alm.handle.core.domain.entity.rs.HomePageCountData;
import com.alm.handle.mapper.SysDevInfoMapper;
import com.alm.handle.service.HomePageService;
import com.alm.handle.util.SoketEleKey;
import com.alm.system.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HomePageServiceImpl implements HomePageService {
    @Resource
    SysDevInfoMapper sysDevInfoMapper;
    @Resource
    SysUserMapper userMapper;
    @Autowired
    RedisCache redisCache;
    @Override
    public HomePageCountData countHomePageData() {
        Long commid = null;
        QueryWrapper queryWrapper = new QueryWrapper();
        QueryWrapper infoWrapper = new QueryWrapper();
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            commid = SecurityUtils.getDeptId();
            queryWrapper.eq("dept_id", commid);
            infoWrapper.eq("section_id", commid);
        }
        HomePageCountData home = sysDevInfoMapper.querHomePage(commid);
        queryWrapper.eq("del_flag", "0");
        Long userCount = userMapper.countUser(commid);
        home.setSumUserNumber(userCount);
        infoWrapper.select("device_id");
        List<SysDevInfo> devInfos = sysDevInfoMapper.selectList(infoWrapper);
        List<String> devMacs=devInfos.stream().map(SysDevInfo ::getDeviceId).collect(Collectors.toList());
        Integer exNumber=0;
        for (String devid:devMacs){
            String ex_key= SoketEleKey.EX_ENERY+devid;
            if(redisCache.hasKey(ex_key)){
                exNumber+=1;
            }
        }
        home.setExDevCount(exNumber);
        return home;
    }
}
